package com.jfinal.bbsapp.common.kit;

import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.HttpKit;
import com.jfinal.weixin.sdk.api.AccessTokenApi;
import com.jfinal.wxaapp.WxaConfigKit;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class WxUtils {
	private static final Logger logger = Logger.getLogger(WxUtils.class);
	
	//获取小程序openid
	public static String getopenid(String appid,String secret,String code) {
		String jsCode2sessionUrl = "https://api.weixin.qq.com/sns/jscode2session";
		String openid= "";
		try {
			OkHttpClient client = new OkHttpClient();
			String url = jsCode2sessionUrl+"?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
			Request request = new Request.Builder().url(url).get().build();
			//{"errcode":0,"errmsg":"xxxxx","session_key":"xxxxx","openid":"xxxxxx"}
			//{"errcode":40029,"errmsg":"invalid code, rid: 65502e8c-41409f22-525e1144"}
		    try (Response response = client.newCall(request).execute()) {
			    ResponseBody responseBody = response.body();
			    if (responseBody != null) {
			        String res = responseBody.string();
			        JSONObject resobj = JSON.parseObject(res);
			        int errcode = resobj.getIntValue("errcode");
					if(errcode == 0) {
						openid = resobj.getString("openid");
						System.out.println("openid------>"+openid);
					}
			    }
			}
		} catch (Exception e) {
			logger.error("------Exception------", e);
		}
		return openid;
	}
	
	@MyAnnotation(memo="获取微信token")
	public static String getwxtoken(String appid,String secret) {
		String access_token ="";
		String URL = "https://api.weixin.qq.com/cgi-bin/token";
		Map<String,String > headers = new HashMap<>();
		headers.put("content-type", "application/json;encoding=utf-8"); 
		Map<String ,String > queryParams = new HashMap<>();
	      queryParams.put("grant_type","client_credential");
	      queryParams.put("appid",appid);
	      queryParams.put("secret",secret);
		try {
			String jsonStr = HttpKit.get(URL,queryParams,headers);//通过URL查询返回结果
            @SuppressWarnings("unchecked")
			Map<String, Object> temp = JsonUtils.parse(jsonStr, Map.class);
            access_token = (String) temp.get("access_token");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
		return access_token;
	}
	
	//获取小程序access_token
	public static String getaccess_token(String appid,String secret) {
		String access_token= "";
		try {
			//先获取access_token//{"access_token":"******","expires_in":7200}
			OkHttpClient client = new OkHttpClient();
			String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
			Request request = new Request.Builder().url(url).get().build();
			try (Response response = client.newCall(request).execute()) {
			    ResponseBody responseBody = response.body();
			    if (responseBody != null) {
			        String res = responseBody.string();
			        JSONObject resobj = JSON.parseObject(res);
			        int errcode = resobj.getIntValue("errcode");
					if(errcode == 0) {
						access_token = resobj.getString("access_token");
				        //System.out.println("access_token------>"+access_token);
					}
			    }
			}
		} catch (Exception e) {
			logger.error("------Exception------", e);
		}
		return access_token;
	}
	
	//获取小程序access_token
	public static String getaccess_token2(String appid,String secret) {
		/*WxaConfig wc = new WxaConfig();
		wc.setAppId(appid);
		wc.setAppSecret(secret);
		WxaConfigKit.setWxaConfig(wc);*/
		WxaConfigKit.setThreadLocalAppId(appid);
        String accessTokenStr = AccessTokenApi.getAccessTokenStr();
        System.out.println("access_token------>"+accessTokenStr);
		return accessTokenStr;
	}
	
}
